<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/24
 * Time: 11:00
 */

namespace App\Rep;


use App\Models\FinishProduct;
use App\Models\Order;
use App\Models\SemiFinishProduct;
use Illuminate\Support\Facades\DB;

class SemiFinishProductRep
{

    /**
     * 获取半成品列表
     * @param $params
     */
    public function getSemiFinishProductListRep($params){

        $list = SemiFinishProduct::Search($params)
            ->with(['order'])
            ->orderBy('id','desc')->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 半成品加入成品库
     * @param $params
     */
    public function addFinishProductRep($params){
        //p($params);
        DB::beginTransaction();
        try{
            foreach ($params['ids'] as $k=>$v){
                $semi = SemiFinishProduct::where('id',$v)->with('order')->first();
                $order_shafa = DB::table('order_shafa')->where('order_id',$semi->order_id)->first();
                $semi->is_del = 1;
                $semi->save();
                $finishProductRep = new FinishProductRep();
                $finishProductRep->addFinishProductRep(
                    $semi->order_id,
                    $order_shafa->cases_num,
                    $params['warehouse_id'],
                    $params['goods_shelf_id'],
                    $semi->order->model_number_id,
                    $semi->order->specification_id,
                    $semi->order->color_id,
                    $semi->order->direction,
                    $semi->order->customer_id,
                    $semi->order->is_stock_up,
                    $params['image_arr']??[]
                );
                $order = Order::where('id',$semi->order_id)->first();
                $order->production_status = 3;
                $order->save();
            }

            DB::commit();
            return ['code'=>0,'data'=>'','msg'=>'success'];

        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>'','msg'=>$exception->getMessage()];
        }
    }

    /**
     * 补录订单直接添加到成品库
     */
    public function replenishmentAddFinishProductRep($order,$num,$warehouse_id,$goods_shelf_id){
        $finishProductRep = new FinishProductRep();
        return $finishProductRep->addFinishProductRep($order->id,$num,$warehouse_id,$goods_shelf_id,$order->model_number_id,$order->specification_id,$order->color_id,$order->direction,$order->customer_id,$order->is_stock_up);
    }
}
